package com.zbkj.crmeb.export.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.utils.ExcelUtil;
import com.utils.PriceUtil;
import com.zbkj.crmeb.agent.request.SettlementRequest;
import com.zbkj.crmeb.agent.response.SettlementResponse;
import com.zbkj.crmeb.chant.response.SupplierAccountCenterResponse.SupplierBill;
import com.zbkj.crmeb.chant.service.IChannelMerchantAccountService;
import com.zbkj.crmeb.enums.ProductTypeEnum;
import com.zbkj.crmeb.export.service.ExcelService;
import com.zbkj.crmeb.export.vo.*;
import com.zbkj.crmeb.finance.request.GetListRequest;
import com.zbkj.crmeb.finance.request.UserExtractSearchRequest;
import com.zbkj.crmeb.finance.response.UserExtractDetailResponse;
import com.zbkj.crmeb.finance.response.UserRechargeResponse;
import com.zbkj.crmeb.finance.service.UserExtractService;
import com.zbkj.crmeb.merchant.admin.controller.AdminBaseController;
import com.zbkj.crmeb.store.model.*;
import com.zbkj.crmeb.store.request.GetOrderDeliveryListRequest;
import com.zbkj.crmeb.store.request.StoreOrderSearchRequest;
import com.zbkj.crmeb.store.request.StoreProductSearchRequest;
import com.zbkj.crmeb.store.response.StoreProductNormKeywordResponse;
import com.zbkj.crmeb.store.service.*;
import com.zbkj.crmeb.system.service.SystemConfigService;
import com.zbkj.crmeb.system.service.impl.SystemAdminServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


/**
 * 商品表 前端控制器
 */
@Slf4j
@Controller
@RequestMapping("api/admin/export/excel")
@Api(tags = "导出 -- Excel")
public class ExcelController extends AdminBaseController {
    @Autowired
    PriceUtil priceUtil;
    @Autowired
    private ExcelService excelService;
    @Autowired
    SystemConfigService systemConfigService;
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private StoreOrderService storeOrderService;
    @Autowired
    OrderInfoDeliveryService orderInfoDeliveryService;
    @Autowired
    private IChannelMerchantAccountService channelMerchantAccountService;
    @Autowired
    private UserExtractService userExtractService;
    @Autowired
    private SupplierUnmatchBrandService supplierUnmatchBrandService;
    @Autowired
    private SupplierUnmatchCategoryService supplierUnmatchCategoryService;

    @Autowired
    private SystemAdminServiceImpl systemAdminServiceImpl;

    AtomicInteger atom = new AtomicInteger(0);
    final int max = 3;
    /**
     * 商品导出
     * @param request 搜索条件
     * @author Mr.Zhang
     * @since 2020-05-06
     */
    @ApiOperation(value = "供应商商品")
    @RequestMapping(value = "/product", method = RequestMethod.GET)
    public void export(@Validated StoreProductSearchRequest request, HttpServletResponse response){
        try{
            // 保护一下 最多允许10个人同时导出
            if(atom.getAndIncrement()<max){
                PageParamRequest pageParamRequest = new PageParamRequest();
                pageParamRequest.setPage(Constants.DEFAULT_PAGE);
                pageParamRequest.setLimit(BooleanUtils.isTrue(request.getIsImg()) ? Constants.IMG_EXPORT_MAX_LIMIT : Constants.EXPORT_MAX_LIMIT);
                //供应商商品
                List<Integer> isNotEurope = Arrays.asList(ProductTypeEnum.INSIDE.getCode());
                request.setIsNotEurope(isNotEurope);
                List<ProductExcelVo> list = storeProductService.getExprotList(request, pageParamRequest);
                excelService.parseList(list);
                List<SupplierAdminProductExcelVo> supplierAdminProductExcelVoList = Convert.toList(SupplierAdminProductExcelVo.class,list);
                //sheet名称
                ExcelUtil.setSheetName("store");
                //文件名称前缀
                ExcelUtil.setFileName("产品导出");
                ExcelUtil.writeExcelByIsImg(response, supplierAdminProductExcelVoList, SupplierAdminProductExcelVo.class,request.getIsImg());
            }
        }finally {
            atom.decrementAndGet();
        }
    }

    @ApiOperation(value = "商户自建商品")
    @RequestMapping(value = "/inside/product", method = RequestMethod.GET)
    public void exportInsideProductList(@Validated StoreProductSearchRequest request, HttpServletResponse response){
        try{
            // 保护一下 最多允许10个人同时导出
            if(atom.getAndIncrement()<max){
                PageParamRequest pageParamRequest = new PageParamRequest();
                pageParamRequest.setPage(Constants.DEFAULT_PAGE);
                pageParamRequest.setLimit(BooleanUtils.isTrue(request.getIsImg()) ? Constants.IMG_EXPORT_MAX_LIMIT : Constants.EXPORT_MAX_LIMIT);
                request.setIsEurope(ProductTypeEnum.INSIDE.getCode());
                List<ProductExcelVo> list = storeProductService.getExprotList(request, pageParamRequest);
                excelService.parseList(list);
                List<StoreAdminProductExcelVo> storeAdminProductExcelVoList = Convert.toList(StoreAdminProductExcelVo.class,list);
                //sheet名称
                ExcelUtil.setSheetName("store");
                //文件名称前缀
                ExcelUtil.setFileName("产品导出");
                ExcelUtil.writeExcelByIsImg(response, storeAdminProductExcelVoList, StoreAdminProductExcelVo.class,request.getIsImg());
            }
        }finally {
            atom.decrementAndGet();
        }
    }

    /**
     * 订单导出
     * @param request 搜索条件
     */
    @ApiOperation(value = "订单")
    @RequestMapping(value = "/storeOrder", method = RequestMethod.GET)
    public void storeOrderexport(@Validated StoreOrderSearchRequest request, HttpServletResponse response){
        try{
            // 保护一下 最多允许10个人同时导出
            if(atom.getAndIncrement()<max){
                PageParamRequest pageParamRequest = new PageParamRequest();
                pageParamRequest.setPage(Constants.DEFAULT_PAGE);
                pageParamRequest.setLimit(Constants.EXPORT_MAX_LIMIT);
                List<StoreOrderExcelVo> productExcelVoList = storeOrderService.getExportList(request, pageParamRequest,systemAdminServiceImpl.getInfo());
                //sheet名称
                ExcelUtil.setSheetName("订单信息表");
                //文件名称前缀
                ExcelUtil.setFileName("订单导出");
                ExcelUtil.writeExcelByIsImg(response, productExcelVoList, StoreOrderExcelVo.class,request.getIsImg());
//                ExcelUtil.writeExcel(response, productExcelVoList, StoreOrderExcelVo.class);
            }
        }finally {
            atom.decrementAndGet();
        }
    }

    /**
     * 标准库商品导出
     * @param request 搜索条件
     */
    @ApiOperation(value = "标准库商品导出")
    @RequestMapping(value = "/normListExport", method = RequestMethod.GET)
    public void normListExport(StoreProductSearchRequest request, HttpServletResponse response){
        try{
            // 保护一下 最多允许10个人同时导出
            if(atom.getAndIncrement()<max){
                PageParamRequest pageParamRequest = new PageParamRequest();
                pageParamRequest.setPage(Constants.DEFAULT_PAGE);
                pageParamRequest.setLimit(Constants.EXPORT_MAX_LIMIT);
                PageInfo<StoreProductNorm> pageInfo = storeProductService.getNormList(request, pageParamRequest);
                List<StoreProductNormExcelVo> normExcelVoList = excelService.convertStoreProductNormList(pageInfo.getList());
                //sheet名称
                ExcelUtil.setSheetName("标准库商品信息");
                //文件名称前缀
                ExcelUtil.setFileName("标准库商品");
                ExcelUtil.writeExcel(response, normExcelVoList, StoreProductNormExcelVo.class);
            }
        }finally {
            atom.decrementAndGet();
        }
    }

    /**
     * 标准库商品导出
     * @param request 搜索条件
     */
    @ApiOperation(value = "标准库编码导出")
    @RequestMapping(value = "/normCodeListExport", method = RequestMethod.GET)
    public void normCodeListExport(StoreProductSearchRequest request, HttpServletResponse response){
        try{
            // 保护一下 最多允许10个人同时导出
            if(atom.getAndIncrement()<max){
                PageParamRequest pageParamRequest = new PageParamRequest();
                pageParamRequest.setPage(Constants.DEFAULT_PAGE);
                pageParamRequest.setLimit(Constants.EXPORT_MAX_LIMIT);
                PageInfo<StoreProductNorm> pageInfo = storeProductService.getNormList(request, pageParamRequest);
                List<StoreProductNormCodeExcelVo> normCodeList = excelService.convertNormCodeList(pageInfo.getList());
                //sheet名称
                ExcelUtil.setSheetName("标准库编码信息");
                //文件名称前缀
                ExcelUtil.setFileName("标准库编码");
                ExcelUtil.writeExcel(response, normCodeList, StoreProductNormCodeExcelVo.class);
            }
        }finally {
            atom.decrementAndGet();
        }
    }


    /**
     * 标准库商品导出
     * @param request 搜索条件
     */
    @ApiOperation(value = "商品编码导出")
    @RequestMapping(value = "/productCodeExport", method = RequestMethod.GET)
    public void productCodeExport(StoreProductSearchRequest request, HttpServletResponse response){
        try{
            // 保护一下 最多允许10个人同时导出
            if(atom.getAndIncrement()<max){
                request.setPageNow(Constants.DEFAULT_PAGE);
                request.setPageSize(Constants.EXPORT_MAX_LIMIT);
                PageInfo<StoreProductNormKeywordResponse> pageNormKeywords = storeProductService.pageNormKeywords(request);

                List<StoreProductCodeExcelVo> productCodeList = excelService.convertProductCodeList(pageNormKeywords.getList());
                //sheet名称
                ExcelUtil.setSheetName("商品编码信息");
                //文件名称前缀
                ExcelUtil.setFileName("商品编码");
                ExcelUtil.writeExcel(response, productCodeList, StoreProductCodeExcelVo.class);
            }
        }finally {
            atom.decrementAndGet();
        }
    }

    /**
     * 商户流水列表导出
     * @param merId
     * @param type
     * @param request
     * @param response
     */
    @ApiOperation(value = "商户流水列表导出")
    @RequestMapping(value = "/merFlowExport", method = RequestMethod.GET)
    public void merFlowExport(@ApiParam(value="商户id ", required = true)Integer merId, @ApiParam(value="类型:1 可用余额;2 可提现余额;3 已冻结金额", required = true)Integer type, PageParamRequest request, HttpServletResponse response){
        try{
            // 保护一下 最多允许10个人同时导出
            if(atom.getAndIncrement()<max){
                request.setPage(Constants.DEFAULT_PAGE);
                request.setLimit(Constants.EXPORT_MAX_LIMIT);
                List<MerFlowExcelVo> merFlowList = excelService.getMerFlowList(merId,type,request);
                //sheet名称
                ExcelUtil.setSheetName("商户流水信息");
                //文件名称前缀
                ExcelUtil.setFileName("商户流水");
                ExcelUtil.writeExcel(response, merFlowList, MerFlowExcelVo.class);
            }
        }finally {
            atom.decrementAndGet();
        }
    }

    /**
     * 商户结算数据导出
     */
    @ApiOperation(value = "商户结算数据导出")
    @GetMapping(value = "/merSettlementExport")
    public void merSettlementExport(GetListRequest request, HttpServletResponse response){
        try{
            // 保护一下 最多允许10个人同时导出
            if(atom.getAndIncrement()<max){
                request.setPage(Constants.DEFAULT_PAGE);
                request.setLimit(Constants.EXPORT_MAX_LIMIT);
                List<UserRechargeResponse> merSettlementList = excelService.getMerSettlementList(request);
                //sheet名称
                ExcelUtil.setSheetName("商户结算信息");
                //文件名称前缀
                ExcelUtil.setFileName("商户结算");
                if(request.getTradeType() == 1){
                    List<RechargeExcelVo> rechargeExcelVoList = merSettlementList.stream().map(e -> {
                        RechargeExcelVo rechargeExcelVo = new RechargeExcelVo();
                        BeanUtil.copyProperties(e, rechargeExcelVo);
                        rechargeExcelVo.setRechargeType(Objects.equals(rechargeExcelVo.getRechargeType(), "routine") ? "线上充值" : "线下充值");
                        return rechargeExcelVo;
                    }).collect(Collectors.toList());
                    ExcelUtil.writeExcel(response, rechargeExcelVoList, RechargeExcelVo.class);
                }else if (request.getTradeType() == 2) {
                    List<WithdrawalExcelVo> withdrawalExcelVoList = merSettlementList.stream().map(e -> {
                        //-1 未通过 0 审核中 1 已提现
                        WithdrawalExcelVo withdrawalExcelVo = new WithdrawalExcelVo();
                        BeanUtil.copyProperties(e, withdrawalExcelVo, "status");
                        if (e.getStatus() == -1) {
                            withdrawalExcelVo.setStatus("未通过");
                        } else if (e.getStatus() == 0) {
                            withdrawalExcelVo.setStatus("审核中");
                        } else if (e.getStatus() == 1) {
                            withdrawalExcelVo.setStatus("已提现");
                        }
                        return withdrawalExcelVo;
                    }).collect(Collectors.toList());
                    ExcelUtil.writeExcel(response, withdrawalExcelVoList, WithdrawalExcelVo.class);
                }
            }
        }finally {
            atom.decrementAndGet();
        }
    }

    @ApiOperation(value = "物流导出")
    @GetMapping(value = "/logisticsExport")
    public void logisticsExport(@Validated GetOrderDeliveryListRequest request, HttpServletResponse response){
        try{
            // 保护一下 最多允许10个人同时导出
            if(atom.getAndIncrement()<max){
                PageParamRequest pageParamRequest = new PageParamRequest();
                pageParamRequest.setPage(Constants.DEFAULT_PAGE);
                pageParamRequest.setLimit(Constants.EXPORT_MAX_LIMIT);
                List<StoreOrderInfo> logisticsList = orderInfoDeliveryService.getLogisticsList(request, pageParamRequest);
                List<LogisticsExcelVo> logisticsExcelVoList = excelService.logisticsExport(logisticsList);
                //sheet名称
                ExcelUtil.setSheetName("物流信息表");
                //文件名称前缀
                ExcelUtil.setFileName("物流导出");
                ExcelUtil.writeExcelByIsImg(response, logisticsExcelVoList, LogisticsExcelVo.class,request.getIsImg());
            }
        }finally {
            atom.decrementAndGet();
        }
    }

    /**
     * 服务商流水列表导出
     */
    @ApiOperation(value = "服务商流水列表导出")
    @RequestMapping(value = "/agentFlowExport", method = RequestMethod.GET)
    public void agentFlowExport(@ApiParam(value="商户id ", required = true)Integer agentId,@ApiParam(value="类型:2 可提现余额;3 已冻结金额", required = true)Integer type, PageParamRequest request, HttpServletResponse response){
        try{
            // 保护一下 最多允许10个人同时导出
            if(atom.getAndIncrement()<max){
                request.setPage(Constants.DEFAULT_PAGE);
                request.setLimit(Constants.EXPORT_MAX_LIMIT);
                List<MerFlowExcelVo> merFlowList = excelService.getAgentFlowList(agentId,type,request);
                //sheet名称
                ExcelUtil.setSheetName("服务商流水信息");
                //文件名称前缀
                ExcelUtil.setFileName("服务商流水");
                ExcelUtil.writeExcel(response, merFlowList, MerFlowExcelVo.class);
            }
        }finally {
            atom.decrementAndGet();
        }
    }

    /**
     * 服务商结算数据导出
     */
    @ApiOperation(value = "服务商结算数据导出")
    @GetMapping(value = "/agentSettlementExport")
    public void agentSettlementExport(SettlementRequest request, HttpServletResponse response){
        try{
            // 保护一下 最多允许10个人同时导出
            if(atom.getAndIncrement()<max){
                request.setPage(Constants.DEFAULT_PAGE);
                request.setLimit(Constants.EXPORT_MAX_LIMIT);
                List<SettlementResponse> merSettlementList = excelService.getAgentSettlementList(request);
                //sheet名称
                ExcelUtil.setSheetName("服务商结算信息");
                //文件名称前缀
                ExcelUtil.setFileName("服务商结算");
                List<AgentWithdrawalExcelVo> withdrawalExcelVoList = merSettlementList.stream().map(e -> {
                    //-1 未通过 0 审核中 1 已提现
                    AgentWithdrawalExcelVo withdrawalExcelVo = new AgentWithdrawalExcelVo();
                    BeanUtil.copyProperties(e, withdrawalExcelVo, "status","createTime");
                    if (e.getStatus() == -1) {
                        withdrawalExcelVo.setStatus("未通过");
                    } else if (e.getStatus() == 0) {
                        withdrawalExcelVo.setStatus("审核中");
                    } else if (e.getStatus() == 1) {
                        withdrawalExcelVo.setStatus("已提现");
                    }
                    withdrawalExcelVo.setCreateTime(DateFormatUtils.format(e.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                    return withdrawalExcelVo;
                }).collect(Collectors.toList());
                ExcelUtil.writeExcel(response, withdrawalExcelVoList, AgentWithdrawalExcelVo.class);
            }
        }finally {
            atom.decrementAndGet();
        }
    }

    @ApiOperation(value = "供应商财务导出")
    @GetMapping(value = "/flow")
    public void supplierFlowExport(@ApiParam(value="商户id ", required = true)Integer merId,PageParamRequest pageParamRequest, HttpServletResponse response) {
        try {
            if (atom.getAndIncrement() < max) {
                pageParamRequest.setPage(Constants.DEFAULT_PAGE);
                pageParamRequest.setLimit(Constants.EXPORT_MAX_LIMIT);
                List<SupplierBill> billList = channelMerchantAccountService.supplierAccountCenter(merId, pageParamRequest).getOrderList().getList();
                List<SupplierFlowExcelVo> supplierExportList = channelMerchantAccountService.parseSupplierExportList(billList);
                //sheet名称
                ExcelUtil.setSheetName("财务信息");
                //文件名称前缀
                ExcelUtil.setFileName("财务导出");
                ExcelUtil.writeExcel(response, supplierExportList, SupplierFlowExcelVo.class);
            }
        } finally {
            atom.decrementAndGet();
        }
    }

    @ApiOperation(value = "提现申请导出")
    @GetMapping(value = "/userExtractDetailExcel")
    public void userExtractDetailExcel(UserExtractSearchRequest request, PageParamRequest pageParamRequest, HttpServletRequest servletRequest, HttpServletResponse response) {
        try {
            if (atom.getAndIncrement() < max) {
                pageParamRequest.setPage(Constants.DEFAULT_PAGE);
                pageParamRequest.setLimit(Constants.EXPORT_MAX_LIMIT);
                request.setMerId(getMerId(servletRequest));
                List<UserExtractDetailResponse> userExtractDetailExport = userExtractService.getUserExtractDetailExport(request);
                List<UserExtractDetailExcelVo> userExtractDetailExcelVos = Convert.toList(UserExtractDetailExcelVo.class,userExtractDetailExport);
                userExtractDetailExcelVos.stream().forEach(userExtractDetailExcelVo -> {
                    userExtractDetailExcelVo.setCreateTimeStr(DateUtil.format(userExtractDetailExcelVo.getCreateTime(),Constants.DATE_FORMAT));
                    if (userExtractDetailExcelVo.getStatus() == 1){
                        userExtractDetailExcelVo.setStatusStr("已提现");
                    }
                    if (userExtractDetailExcelVo.getStatus() == 0){
                        userExtractDetailExcelVo.setStatusStr("待处理");
                    }
                    if (userExtractDetailExcelVo.getStatus() == -1){
                        userExtractDetailExcelVo.setStatusStr("已拒绝");
                    }
                });
                //sheet名称
                ExcelUtil.setSheetName("提现申请");
                //文件名称前缀
                ExcelUtil.setFileName("提现申请导出");
                ExcelUtil.writeExcel(response, userExtractDetailExcelVos, UserExtractDetailExcelVo.class);
            }
        } finally {
            atom.decrementAndGet();
        }
    }

    @ApiOperation(value = "未匹配品牌导出")
    @RequestMapping(value = "/match/brand", method = RequestMethod.GET)
    public void exportUnMatchBrand(Integer type, HttpServletResponse response){
        try{
            // 保护一下 最多允许10个人同时导出
            if(atom.getAndIncrement()<max){
                PageParamRequest pageParamRequest = new PageParamRequest();
                pageParamRequest.setPage(Constants.DEFAULT_PAGE);
                pageParamRequest.setLimit(Constants.EXPORT_MAX_LIMIT);
                PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
                List<SupplierUnmatchBrand> unMatchBrandList = supplierUnmatchBrandService.list(Wrappers.<SupplierUnmatchBrand>lambdaQuery()
                        .eq(SupplierUnmatchBrand::getIsDel, 0)
                        .eq(type != null, SupplierUnmatchBrand::getType, type)
                );
                List<UnMatchBrandExcelVo> excelVoList = Convert.toList(UnMatchBrandExcelVo.class,unMatchBrandList);
                //sheet名称
                ExcelUtil.setSheetName("brand");
                //文件名称前缀
                ExcelUtil.setFileName("未匹配品牌");
                ExcelUtil.writeExcel(response, excelVoList, UnMatchBrandExcelVo.class);
            }
        }finally {
            atom.decrementAndGet();
        }
    }

    @ApiOperation(value = "未匹配分类导出")
    @RequestMapping(value = "/match/category", method = RequestMethod.GET)
    public void exportUnMatchCategory(Integer type, HttpServletResponse response){
        try{
            // 保护一下 最多允许10个人同时导出
            if(atom.getAndIncrement()<max){
                PageParamRequest pageParamRequest = new PageParamRequest();
                pageParamRequest.setPage(Constants.DEFAULT_PAGE);
                pageParamRequest.setLimit(Constants.EXPORT_MAX_LIMIT);
                PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
                List<SupplierUnmatchCategory> unMatchCategoryList = supplierUnmatchCategoryService.list(Wrappers.<SupplierUnmatchCategory>lambdaQuery()
                        .eq(SupplierUnmatchCategory::getIsDel, 0)
                        .eq(type != null, SupplierUnmatchCategory::getType, type)
                );
                List<UnMatchCategoryExcelVo> excelVoList = Convert.toList(UnMatchCategoryExcelVo.class,unMatchCategoryList);
                //sheet名称
                ExcelUtil.setSheetName("category");
                //文件名称前缀
                ExcelUtil.setFileName("未匹配分类");
                ExcelUtil.writeExcel(response, excelVoList, UnMatchCategoryExcelVo.class);
            }
        }finally {
            atom.decrementAndGet();
        }
    }

}



